package org.moon.framework.autoconfigure.oss.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.ssh.Sftp;
import org.moon.framework.autoconfigure.oss.OssService;
import org.moon.framework.autoconfigure.oss.OssTemplate;
import org.moon.framework.autoconfigure.oss.props.OssProperties;
import org.moon.framework.autoconfigure.oss.utils.FileUtils;

import java.io.File;
import java.util.List;

/**
 * Sftp 文件客户端
 *
 * @author 村口的大爷
 */
public class SftpOssService implements OssService {

    private OssProperties ossProperties;
    private Sftp sftp;

    public SftpOssService(OssProperties ossProperties) {
        this.ossProperties = ossProperties;
        // 补全风格。例如说 Linux 是 /，Windows 是 \
        if (!ossProperties.getBasePath().endsWith(File.separator)) {
            ossProperties.setBasePath(ossProperties.getBasePath() + File.separator);
        }
        // 初始化 Ftp 对象
        this.sftp = new Sftp(ossProperties.getHost(), ossProperties.getPort(), ossProperties.getUserName(), ossProperties.getPassword());
    }


    @Override
    public String upload(byte[] content, String originalName) {
        // 执行写入
        String path = getFilePath(ossProperties.getBasePath(),originalName);
        File file = FileUtils.createTempFile(content);
        sftp.upload(path, file);
        // 拼接返回路径
        String link = formatFileUrl(ossProperties.getDomain(),ossProperties.getId(), path);
        insert(ossProperties.getId(),originalName,link, OssTemplate.FileStorageEnum.SFTP);
        return link;
    }

    @Override
    public void delete(String link) {
        String filePath = getFilePath(link,ossProperties.getDomain(),ossProperties.getId());
        sftp.delFile(filePath);
        delete(ossProperties.getId(),link);
    }

    @Override
    public void batchDelete(List<String> links) {
        for(String link:links){
            delete(link);
        }
    }

    @Override
    public byte[] getContent(String link) {
        File destFile = FileUtils.createTempFile();
        String filePath = getFilePath(link,ossProperties.getDomain(),ossProperties.getId());
        sftp.download(filePath, destFile);
        return FileUtil.readBytes(destFile);
    }
}